package com.cry.todo.action;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.apache.commons.logging.Log;
import org.apache.struts2.ServletActionContext;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;

import com.cry.app.core.log.Logger;
import com.cry.todo.domain.User;
import com.cry.todo.domain.project.Category;
import com.cry.todo.domain.project.Project;
import com.cry.todo.domain.project.ProjectSearch;
import com.cry.todo.domain.project.Status;
import com.cry.todo.service.ProjectService;
import com.cry.todo.service.UserService;
import com.cry.webapp.action.ActionSupport;
import com.cry.webapp.ui.datagrid.DataGrid;
import com.cry.webapp.ui.datagrid.JQGridImpl;
import com.opensymphony.xwork2.Action;

public class ProjectSearchAction extends ActionSupport  {
	@Logger 
	public Log log;
	
    private HttpServletRequest request = ServletActionContext.getRequest();
    private HttpServletResponse response = ServletActionContext.getResponse(); 
    {
        response.setCharacterEncoding("UTF-8");
    }

	/**
	 * IoC injected services
	 */
	@Autowired
	private ProjectService projectService;
	@Autowired
	private UserService userService;

	@Valid
	private ProjectSearch item;
	public int wasSearch = 0;
	private ArrayList<User> usersList;
	private ArrayList<Category> categoriesList;
	private ArrayList<Status> statusesList;
	boolean prepared = false;
	private JQGridImpl dataGrid = new JQGridImpl();
	private int needSearchResult = 0;

	@Override
	public void prepare() throws Exception {
        //request.setCharacterEncoding("UTF-8");

        if(wasSearch == 0) {
			log.trace("It was not a search");
			item = projectService.getLasProjectSearch();
		} 
		
		if(item == null ){
			item = new ProjectSearch();
		}
		prepared = true;
	}

	/**
	 * Action search
	 * @return
	 */
	public String search() {
		/*if(wasSearch != 0) {
			projectService.saveLastProjectSearch(item);
		}

		projectService.search(item);*/

		return Action.SUCCESS;
	}

	public String jsonShowProjects() throws Exception {

		if(wasSearch != 0) {
			projectService.saveLastProjectSearch(item);
		}

        DataGrid dataTable = new JQGridImpl();
        dataTable.init(request);

        //dataTable.setTotalRecord(projectService.countChildren(getProjectNumber()));
		
		Set<Project> result = new LinkedHashSet<Project>(
					projectService.search(item, dataTable.getStartRow(), dataTable.getDisplayRow(), dataTable.getOrderColumn(), dataTable.getOrderDir())
					);
		dataTable.setTotalRecord(result.size());
				
        response.setContentType("application/json");
        response.setStatus(HttpServletResponse.SC_OK);

		//dataTable.setColumns(dataTableColumns);
		dataTable.setList(result);
		HashMap<String, Object> userData = new HashMap<String, Object>(); 
//		userData.put("parent", item.getParentProject());

		dataTable.setUserData(userData);

		response.setContentType("application/json");
        response.setStatus(HttpServletResponse.SC_OK);
        ObjectMapper mapper = new ObjectMapper(); // can reuse, share globally
        mapper.writeValue(response.getWriter(), dataTable.buildJSONResponse());
		
		return Action.NONE;
	}
	
	public ProjectSearch getItem() {
		return item;
	}

	public void setItem(ProjectSearch item) {
		this.item = item;
	}
	
	/**
	 * Retrieve list of users
	 * @return
	 */
	public ArrayList<User> getUsersList() {
		if( usersList == null) {
			usersList = userService.loadAll();
		}
		return usersList;
	}

	public void setUsersIds(ArrayList<Integer> ids) throws Exception {
		log.debug("");
		if (!prepared || ids == null) return;
		item.setUsers(ids);
	}

	public void setCreatorsIds(ArrayList<Integer> ids) throws Exception {
		log.debug("");
		if (!prepared || ids == null) return;
		item.setCreators(ids);
	}

	public void setSupervisorsIds(ArrayList<Integer> ids) throws Exception {
		log.debug("");
		if (!prepared || ids == null) return;
		item.setSupervisors(ids);
	}

	/**
	 * Retrieve project categories list
	 * @return
	 */
	public ArrayList<Category> getCategoriesList() {
		if(categoriesList == null) {
			categoriesList = new ArrayList(projectService.loadCategories());
		}
		return categoriesList;
	}

	public void setCategoriesIds(ArrayList<Integer> ids) throws Exception {
		log.debug("");
		if (!prepared || ids == null) return;
		item.setCategories(ids);
	}

	/**
	 * Retrieve project statuses list
	 * @return
	 */
	public ArrayList<Status> getStatusesList() {
		if(statusesList == null) {
			statusesList = new ArrayList(projectService.loadStatuses());
		}
		return statusesList;
	}
	
	public void setStatusIds(ArrayList<Integer> ids) throws Exception {
		log.debug("");
		if (!prepared || ids == null) return;
		item.setStatuses(ids);
	}

	public int getWasSearch() {
		return wasSearch;
	}

	public void setWasSearch(int wasSearch) {
		this.wasSearch = wasSearch;
	}

	public void setWasSearch(String wasSearch) {
		//this.wasSearch = wasSearch;
		log.debug(wasSearch);
	}

	public JQGridImpl getDataGrid() {
		return dataGrid;
	}

	public void setDataGrid(JQGridImpl dataGrid) {
		this.dataGrid = dataGrid;
	}

	public int getNeedSearchResult() {
		return needSearchResult;
	}

	public void setNeedSearchResult(int needSearchResult) {
		this.needSearchResult = needSearchResult;
	}

	public String getCreateFrom(String date) throws ParseException {
		return "helló";
	}
	public void setCreateFrom(String date) throws ParseException {
		if (!prepared || date != null || date.length() == 0) return;
		DateFormat formatter = new SimpleDateFormat(getText("dateformat.java.long.sanstime"));
		item.setCreateFrom((Date)formatter.parse(date));
	}
	
	public void setCreateTo(String date) throws ParseException {
		if (!prepared || date != null || date.length() == 0) return;
		DateFormat formatter = new SimpleDateFormat(getText("dateformat.java.long.sanstime"));
		item.setCreateTo((Date)formatter.parse(date));
	}
	
}
